/**
 * Copyright (c) 2016-2019  All rights reserved.
 *
 * https://www.yuncheng.io
 *
 * 版权所有，侵权必究！
 */

package io.yuncheng.modules.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.yuncheng.common.annotation.DataFilter;
import io.yuncheng.common.utils.Constant;
import io.yuncheng.common.utils.LogTypeConstant;
import io.yuncheng.common.utils.PageUtils;
import io.yuncheng.common.utils.Query;
import io.yuncheng.modules.sys.dao.SysUserDao;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.*;
import io.yuncheng.modules.sys.service.*;
import io.yuncheng.modules.sys.shiro.ShiroUtils;
import io.yuncheng.modules.sys.entity.SysDeptEntity;
import io.yuncheng.modules.sys.entity.SysRoleEntity;
import io.yuncheng.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysDeptService sysDeptService;
	@Resource
	private SysRoleService sysRoleService;

	@Resource
	private SysOperationLogService sysOperationLogService;

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	@DataFilter(subDept = true, user = false)
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Object deptId = params.get("deptId");

		IPage<SysUserEntity> page = this.page(
			new Query<SysUserEntity>().getPage(params),
			new QueryWrapper<SysUserEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
					.eq(deptId!=null,"dept_id",deptId)
					.ne("user_id",1L)
				.apply(params.get(Constant.SQL_FILTER) != null, (String)params.get(Constant.SQL_FILTER))
		);

		for(SysUserEntity sysUserEntity : page.getRecords()){
			SysDeptEntity sysDeptEntity = sysDeptService.getById(sysUserEntity.getDeptId());
			if(sysDeptEntity!=null){
				sysUserEntity.setDeptName(sysDeptEntity.getName());
			}
			List<Long> longs = sysUserRoleService.queryRoleIdList(sysUserEntity.getUserId());
			if(ObjectUtils.isEmpty(longs)){
				continue;
			}
			Collection<SysRoleEntity> sysRoleEntities = sysRoleService.listByIds(longs);
			String collect = sysRoleEntities.stream().map(SysRoleEntity::getRoleName).collect(Collectors.joining(","));
			sysUserEntity.setRuleListStr(collect);
			sysUserEntity.setRoleIdList(longs);
		}
		return new PageUtils(page);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUser(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setSalt(salt);
		user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
		this.save(user);
		sysOperationLogService.saveLog(LogTypeConstant.USER,"添加用户\""+ user.getUsername() + "\",ID \"" + user.getUserId()+"\"");
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			SysUserEntity userEntity = this.getById(user.getUserId());
			user.setPassword(ShiroUtils.sha256(user.getPassword(), userEntity.getSalt()));
		}
		this.updateById(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
		String rule = " ";
		if(!ObjectUtils.isEmpty(user.getRoleIdList())){
			Collection<SysRoleEntity> sysRoleEntities = sysRoleService.listByIds(user.getRoleIdList());
			rule = sysRoleEntities.stream().map(SysRoleEntity::getRoleName).collect(Collectors.joining(","));
		}
		sysOperationLogService.saveLog(LogTypeConstant.ROLE,"授权"+ user.getUsername() + "为 " + rule );
	}


	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
        	new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

}
